package cn.dzhang.rcp.hyperbola.actions;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;

import cn.dzhang.rcp.hyperbola.common.UIConstants;
import cn.dzhang.rcp.hyperbola.editors.ChatEditor;
import cn.dzhang.rcp.hyperbola.editors.ChatEditorInput;
import cn.dzhang.rcp.hyperbola.model.ContactEntry;

public class ChatAction extends Action implements ISelectionListener,
		IWorkbenchAction {

	private final IWorkbenchWindow window;
	public static final String ID = "cn.dzhang.rcp.hyperbola.actions.ChatAction";
	private IStructuredSelection selection;

	public ChatAction(IWorkbenchWindow window) {
		super();
		this.window = window;
		this.window.getSelectionService().addSelectionListener(this);

		setId(ID);
		setActionDefinitionId(ID);
		setText("&Chat");
		setToolTipText("Chat with the selected contact.");
		setImageDescriptor(UIConstants.ImageDescriptors.COMMENTS_ADD_16);
	}

	@Override
	public void run() {
		if (selection == null) {
			MessageDialog.openWarning(null, "选择提示", "请选择要交谈的联系人。");
			setEnabled(false);
			return;
		}

		ContactEntry contat = (ContactEntry) selection.getFirstElement();
		IWorkbenchPage page = window.getActivePage();

		try {
			page.openEditor(new ChatEditorInput(contat.getName()),
					ChatEditor.ID);
		} catch (PartInitException e) {
			e.printStackTrace();
		}

	}

	@Override
	public void dispose() {
		this.window.getSelectionService().removeSelectionListener(this);
	}

	@Override
	public void selectionChanged(IWorkbenchPart part, ISelection _selection) {
		if (_selection instanceof IStructuredSelection) {
			selection = (IStructuredSelection) _selection;
			setEnabled(selection.size() == 1
					&& selection.getFirstElement() instanceof ContactEntry);
		} else {
			setEnabled(false);
		}
	}

}
